/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.iai.v20200303.IaiClient;
import com.tencentcloudapi.iai.v20200303.models.CreatePersonRequest;
import com.tencentcloudapi.iai.v20200303.models.CreatePersonResponse;
import com.tencentcloudapi.iai.v20200303.models.PersonExDescriptionInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.business.domain.Hlry;
import me.zhengjie.business.domain.Pgry;
import me.zhengjie.business.domain.sup.Gsgl;
import me.zhengjie.business.domain.sup.Rygl;
import me.zhengjie.business.repository.GsglRepository;
import me.zhengjie.business.repository.HlryRepository;
import me.zhengjie.business.repository.PgryRepository;
import me.zhengjie.business.repository.RyglRepository;
import me.zhengjie.business.service.HlryService;
import me.zhengjie.business.service.PgryService;
import me.zhengjie.business.service.dto.HlryDto;
import me.zhengjie.business.service.dto.PgryDto;
import me.zhengjie.business.service.dto.RyglQueryCriteria;
import me.zhengjie.business.service.mapstruct.HlryMapper;
import me.zhengjie.business.service.mapstruct.PgryMapper;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.face.config.FaceConfig;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author xiahongbo
* @date 2022-04-11
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class HlryServiceImpl implements HlryService {

    private final PasswordEncoder passwordEncoder;
    private final UserRepository userRepository;
    private final HlryRepository hlryRepository;
    private final RyglRepository ryglRepository;
    private final GsglRepository gsglRepository;
    private final HlryMapper hlryMapper;

    @Override
    public Map<String,Object> queryAll(RyglQueryCriteria criteria, Pageable pageable){
        if(SecurityUtils.getCurrentUserId() != 1) {
            Gsgl gsgl = gsglRepository.queryGsgl(SecurityUtils.getCurrentUserId());
            criteria.setBisGsglId(gsgl.getBisGsglId());
        }
        Page<Hlry> page = hlryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(hlryMapper::toDto));
    }

    @Override
    public List<HlryDto> queryAll(RyglQueryCriteria criteria){
        return hlryMapper.toDto(hlryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public HlryDto findById(Long bisRyglId) {
        Hlry hlry = hlryRepository.findById(bisRyglId).orElseGet(Hlry::new);
        ValidationUtil.isNull(hlry.getBisRyglId(),"Hlry","bisRyglId",bisRyglId);
        return hlryMapper.toDto(hlry);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HlryDto create(Hlry resources) {
        Rygl isExist = ryglRepository.findByAndBisRyglLxdh(resources.getBisRyglLxdh());
        if(isExist != null) {
            throw new BadRequestException("手机号["+isExist.getBisRyglLxdh()+"]已经存在");
        }

        UserDetails userDetails = SecurityUtils.getCurrentUser();
        JSONObject userJson = new JSONObject(new JSONObject(userDetails).get("user"));
        JSONObject deptJson = new JSONObject(userJson.get("dept"));
        String id = deptJson.getStr("id");

        // 新增商保公司，需要模拟用户插入
        User user = new User();
        user.setUsername(resources.getBisRyglLxdh());
        user.setPassword(passwordEncoder.encode(DefaultUtil.PASSWORD));
        user.setNickName(resources.getBisRyglXm());
        user.setPhone(resources.getBisRyglLxdh());
        user.setEnabled(true);
        user.setIsAdmin(false);

        // 新增用户，模拟护理公司部门
        Dept dept = new Dept();
        dept.setId(Long.parseLong(id));
        user.setDept(dept);

        // 新增用户，模拟护理人员角色
        Set<Role> setRole = new HashSet<Role>();
        Role role = new Role();
        role.setId(DefaultUtil.ROLE_HLRY);
        setRole.add(role);
        user.setRoles(setRole);

        user = userRepository.save(user);

        Gsgl gsgl = gsglRepository.queryGsgl(SecurityUtils.getCurrentUserId());
        resources.setGsgl(gsgl);
        resources.setBisRyglUserId(user.getId());

        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setBisRyglId(snowflake.nextId());
        if(hlryRepository.findByBisRyglZjhm(resources.getBisRyglZjhm()) != null){
            throw new EntityExistException(Hlry.class,"BIS_RYGL_ZJHM",resources.getBisRyglZjhm());
        }
        return hlryMapper.toDto(hlryRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Hlry resources) {
        log.info("update resources : {} ", resources);
        Hlry hlry = hlryRepository.findById(resources.getBisRyglId()).orElseGet(Hlry::new);
        ValidationUtil.isNull( hlry.getBisRyglId(),"Hlry","id",resources.getBisRyglId());
        Hlry hlry1 = hlryRepository.findByBisRyglZjhm(resources.getBisRyglZjhm());
        if(hlry1 != null && !hlry1.getBisRyglId().equals(hlry.getBisRyglId())){
            throw new EntityExistException(Hlry.class,"BIS_RYGL_ZJHM",resources.getBisRyglZjhm());
        }

        hlry.copy(resources);
        hlryRepository.save(hlry);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long bisRyglId : ids) {
            hlryRepository.deleteById(bisRyglId);
        }
    }

    @Override
    public void download(List<HlryDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (HlryDto hlry : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("身份证", hlry.getBisRyglZjhm());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}